package com.video.information.data

import com.video.information.data.dao.MainPageDao
import com.video.information.data.network.InformationNetwork
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class MainPageRepository private constructor(private val mainPageDao: MainPageDao, private val informationNetwork: InformationNetwork){

    suspend fun refreshHomePageRecommend(url: String) = requestHomePageRecommend(url)

    /**
     * 在IO协程运行
     */
    private suspend fun requestHomePageRecommend(url: String) = withContext(Dispatchers.IO) {
        val response = informationNetwork.fetchHomePageRecommend(url)
        mainPageDao.cacheHomePageRecommend(response)
        response
    }

    companion object {

        private var repository: MainPageRepository? = null

        fun getInstance(dao: MainPageDao, network: InformationNetwork): MainPageRepository {
            if (repository == null) {
                synchronized(MainPageRepository::class.java) {
                    if (repository == null) {
                        repository = MainPageRepository(dao, network)
                    }
                }
            }

            return repository!!
        }
    }
}